package com.foreveross.bsl.mongodb.domain;

import java.io.Serializable;
import java.util.List;

import org.springframework.data.annotation.Transient;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;

import com.foreveross.bsl.common.utils.context.ContextThead;
import com.foreveross.bsl.common.utils.enums.OperatEnum;
import com.foreveross.bsl.common.utils.factory.InstanceFactory;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.mongodb.domain.repository.EntityRepository;
import com.foreveross.bsl.mongodb.domain.repository.EntityRepositoryFactoryBean;
import com.foreveross.bsl.mongodb.domain.repository.EntityRepositoryImpl;

@SuppressWarnings("rawtypes")
public abstract class Entity {

	@Transient
	private EntityRepository entityRepository;

	@Deprecated
	public Class getEntityRepositoryClass() {
		return null;
	};

	public <T extends EntityRepository> T getEntityRepository(Class<T> clazz) {
		if (entityRepository == null) {
			if (clazz == null) {
				throw new RuntimeException("entity repository calss is not set.");
			}
			entityRepository = InstanceFactory.getContextInstance(clazz);
		}

		// ContextThead.setThreadVar(this.getRegisterNo());
		ContextThead.setThreadClasss(this.getClass());
		return (T) entityRepository;
	}

	@SuppressWarnings("unchecked")
	public EntityRepository getEntityRepository() {
		// ContextThead.setThreadVar(this.getRegisterNo());
		ContextThead.setThreadClasss(this.getClass());

		MongoOperations mongoOperations = InstanceFactory.getContextInstance(MongoTemplate.class);
		EntityRepositoryFactoryBean fb = InstanceFactory.getContextInstance(EntityRepositoryFactoryBean.class);
		MongoRepositoryFactory f = (MongoRepositoryFactory) fb.getFactoryInstance(mongoOperations);
		return new EntityRepositoryImpl(f.getEntityInformation(getClass()), mongoOperations);
	}

	/**
	 * Saves a given entity. Use the returned instance for further operations as
	 * the save operation might have changed the entity instance completely.
	 * 
	 * @param entity
	 * @return the saved entity
	 */
	@SuppressWarnings("unchecked")
	public Entity save() {
		return (Entity) getEntityRepository().save(this);
	}

	/**
	 * Saves all given entities.
	 * 
	 * @param entities
	 * @return the saved entities
	 * @throws IllegalArgumentException
	 *             in case the given entity is (@literal null}.
	 */
	@SuppressWarnings("unchecked")
	public Iterable<Entity> save(Iterable<Entity> entities) {
		return getEntityRepository().save(entities);
	}

	/**
	 * Retrives an entity by its id.
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @return the entity with the given id or {@literal null} if none found
	 * @throws IllegalArgumentException
	 *             if {@code id} is {@literal null}
	 */
	@SuppressWarnings("unchecked")
	public <ID extends Serializable> Entity findOne(ID id) {
		return (Entity) getEntityRepository().findOne(id);
	}

	/**
	 * Returns whether an entity with the given id exists.
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @return true if an entity with the given id exists, alse otherwise
	 * @throws IllegalArgumentException
	 *             if {@code id} is {@literal null}
	 */
	@SuppressWarnings("unchecked")
	public <ID extends Serializable> boolean exists(ID id) {
		return getEntityRepository().exists(id);
	}

	/**
	 * Returns all instances of the type.
	 * 
	 * @return all entities
	 */
	@SuppressWarnings("unchecked")
	public Iterable<Entity> findAll() {
		return getEntityRepository().findAll();
	}

	/**
	 * Returns all instances of the type with the given IDs.
	 * 
	 * @param ids
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <ID extends Serializable> Iterable<Entity> findAll(Iterable<ID> ids) {
		return getEntityRepository().findAll(ids);
	}

	/**
	 * Returns the number of entities available.
	 * 
	 * @return the number of entities
	 */
	public long count() {
		return getEntityRepository().count();
	}

	/**
	 * Deletes the entity with the given id.
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @throws IllegalArgumentException
	 *             in case the given {@code id} is {@literal null}
	 */
	@SuppressWarnings("unchecked")
	public <ID extends Serializable> void delete(ID id) {
		getEntityRepository().delete(id);
	}

	/**
	 * Deletes a given entity.
	 * 
	 * @param entity
	 * @throws IllegalArgumentException
	 *             in case the given entity is (@literal null}.
	 */
	@SuppressWarnings("unchecked")
	public void delete() {
		getEntityRepository().delete(this);
	}

	/**
	 * Deletes the given entities.
	 * 
	 * @param entities
	 * @throws IllegalArgumentException
	 *             in case the given {@link Iterable} is (@literal null}.
	 */
	@SuppressWarnings("unchecked")
	public void delete(Iterable<? extends Entity> entities) {
		getEntityRepository().delete(entities);
	}

	/**
	 * Deletes all entities managed by the repository.
	 */
	public void deleteAll() {
		getEntityRepository().deleteAll();
	}

	/**
	 * Returns all entities sorted by the given options.
	 * 
	 * @param sort
	 * @return all entities sorted by the given options
	 */
	@SuppressWarnings("unchecked")
	public Iterable<Entity> findAll(Sort sort) {
		return getEntityRepository().findAll(sort);
	}

	/**
	 * Returns a {@link Page} of entities meeting the paging restriction
	 * provided in the {@code Pageable} object.
	 * 
	 * @param pageable
	 * @return a page of entities
	 */
	@SuppressWarnings("unchecked")
	public Page<Entity> findAll(Pageable pageable) {
		return getEntityRepository().findAll(pageable);
	}

	public List findListByQuery(Query query) {
		return getEntityRepository().findListByQuery(query);
	}

	public List findListByProperty(String proName, OperatEnum operat,
			Object value) {
		return getEntityRepository().findListByProperty(proName, operat, value);
	}

	public List findListByProperty(String[] proName, OperatEnum[] operat,
			Object[] value) {
		return getEntityRepository().findListByProperty(proName, operat, value);
	}

	public Page findByQuery(Query query) {
		return getEntityRepository().findByQuery(query);
	}

	public Page findByQuery(Query query, Pageable pageable) {
		return getEntityRepository().findByQuery(query, pageable);
	}

	public Page findByProperty(String proName, OperatEnum operat, Object value,
			Pageable pageable) {
		return getEntityRepository().findByProperty(proName, operat, value,
				pageable);
	}

	public Page findByProperty(String[] proName, OperatEnum[] operat,
			Object[] value, Pageable pageable) {
		return getEntityRepository().findByProperty(proName, operat, value,
				pageable);
	}

	public void deleteByProperty(String proName, OperatEnum operat, Object value) {
		getEntityRepository().deleteByProperty(proName, operat, value);
	}

	public void deleteByProperty(String[] proName, OperatEnum[] operat,
			Object[] value) {
		getEntityRepository().deleteByProperty(proName, operat, value);
	}

	public Page findByQuerySpecs(QuerySpecs querySpecs, Pageable pageable) {
		return getEntityRepository().findByQuerySpecs(querySpecs, pageable);
	}

}
